package com.example.zuoye.controller;

import com.example.zuoye.entity.Book;
//import com.example.zuoye.service.BookService;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

//    @Autowired
//    private BookService bookService;

    private Integer books_id = 5;
    private Integer books_number;
    private Boolean m_flag = false;
    @Autowired
    HttpServletRequest request; //通过注解获取一个request

    @Value("${uploadPathImg}")
    private String uploadPathImg;

    @RequestMapping("/bookManage")
    public String bookManage(HttpSession session,
                             Model model){
//        List<Book> books = bookService.selectBookInfo();
        session.setAttribute("o_book_name","说不尽的废名");
        session.setAttribute("o_book_press","商务印书馆");
        session.setAttribute("o_book_author","陈建军");
        session.setAttribute("o_book_date","2021-11-15");
        session.setAttribute("o_book_number","100");
        session.setAttribute("o_book_image","https://booklibimg.kfzimg.com/data/book_lib_img_v2/user/0/80ee/80eeceb9079af42da2cec2dc498ec471_0_0_0_0_water.jpg");

        List booksInfo = new ArrayList();
        List bookInfo = new ArrayList();

        if (books_number != null){
            String userName = (String) request.getSession().getAttribute("book_name");
            String userPress = (String) request.getSession().getAttribute("book_press");
            String userAuthor = (String) request.getSession().getAttribute("book_author");
            String userDate = (String) request.getSession().getAttribute("book_date");
            Integer userNumber = books_number;
            String userImage = (String) request.getSession().getAttribute("book_image");
            Integer userId = (Integer) request.getSession().getAttribute("book_id");

            if (userName != null && userPress != null && userAuthor != null && userDate != null && userImage != null){
                List bookTarget = new ArrayList();
                bookTarget.add(userName);
                bookTarget.add(userPress);
                bookTarget.add(userAuthor);
                bookTarget.add(userDate);
                bookTarget.add(books_number);
                bookTarget.add(userImage);
                bookTarget.add(userId);
                bookInfo.add(bookTarget);
            }
        }

        for(int i = 0;i < books_id;i++){
            List bookTarget = new ArrayList();
            bookTarget.add(session.getAttribute("o_book_name"));
            bookTarget.add(session.getAttribute("o_book_press"));
            bookTarget.add(session.getAttribute("o_book_author"));
            bookTarget.add(session.getAttribute("o_book_date"));
            bookTarget.add(session.getAttribute("o_book_number"));
            bookTarget.add(session.getAttribute("o_book_image"));
            bookTarget.add(i);
            bookInfo.add(bookTarget);
        }

        booksInfo.add(bookInfo);

        if(m_flag == true){
            System.out.println("执行力m_flag");

            bookInfo = (List)request.getSession().getAttribute("mbooks_Info");
            System.out.println("booksInfo="+bookInfo);
            m_flag = false;
        }
        session.setAttribute("booksInfo",bookInfo);
        model.addAttribute("booksInfo",bookInfo);

        return "bookManage";
    }

    @RequestMapping("/addBook")
    public String addBook(){
        return "addBook";
    }

    private Integer gobal_book_id;

    @RequestMapping("/modifyBook/{book_name}/{book_author}/{book_press}/{book_date}/{book_number}")
    public String modifyBook(@PathVariable(value = "book_name") String book_name,
                             @PathVariable(value = "book_author") String book_author,
                             @PathVariable(value = "book_press") String book_press,
                             @PathVariable(value = "book_date") String book_date,
                             @PathVariable(value = "book_number") Integer book_number,
                             Model model) throws JSONException {

        System.out.println("执行力modifyBook");

        JSONObject bookInfo = new JSONObject();
        bookInfo.put("book_name",book_name);
        bookInfo.put("book_author",book_author);
        bookInfo.put("book_press",book_press);
        bookInfo.put("book_date",book_date);
        bookInfo.put("book_number",book_number);

        System.out.println(bookInfo.getInt("book_number"));
        model.addAttribute("bookInfo",bookInfo);
        return "modifyBook";
    }
//
    @RequestMapping("/bmodifyBook")
    @ResponseBody
    public String bmodifyBook(@RequestParam(value = "book_id") Integer book_id){
        System.out.println("执行了bmodifyBook");
        gobal_book_id = book_id;

        return null;
    }

    @RequestMapping(value = "/umodifyBook")
    public String umodifyBook(@RequestParam(value = "book_image") MultipartFile file,
                              HttpServletRequest request,
                              HttpSession session,
                              Model model) throws JSONException, IOException {
        System.out.println("执行了umodifyBook");

        List books_info = (List)request.getSession().getAttribute("booksInfo");

        Integer book_id = gobal_book_id;
        String book_name = request.getParameter("book_name");
        String book_author = request.getParameter("book_author");
        String book_press = request.getParameter("book_press");
        String book_date = request.getParameter("book_date");
        Integer book_number = Integer.valueOf(request.getParameter("book_number"));
        String book_image = file.getOriginalFilename();

        String fileName = System.currentTimeMillis() + file.getOriginalFilename();
        String upload_file_dir = uploadPathImg;

        File upload_file_dir_file = new File(upload_file_dir);

        // 前端上传的文件复制到希望的位置
        File targetFile = new File(upload_file_dir_file, fileName);
        file.transferTo(targetFile);

        // 上传图片最终的路径(String类型)
        book_image = fileName;

        System.out.println("books_info.get(book_id)="+books_info.get(book_id));
        ArrayList target = new ArrayList();
        target.add(book_name);
        target.add(book_press);
        target.add(book_author);
        target.add(book_date);
        target.add(book_number);
        target.add(book_image);
        books_info.set(book_id,target);
        System.out.println("books_info.get(book_id)="+books_info.get(book_id));

        session.setAttribute("mbooks_Info",books_info);
        m_flag = true;
        return "redirect:/book/bookManage";
    }

    @RequestMapping(value = "/udeleteBook",method = RequestMethod.POST)
    @ResponseBody
    public String udeleteBook(@RequestParam(value = "book_id") Integer book_id) throws JSONException {
        System.out.println("执行了udeleteBookBook");
        System.out.println(book_id);
//        Integer delete_result = bookService.deleteBookInfoById(book_id);
        List books_info = (List)request.getSession().getAttribute("booksInfo");
        Boolean flag = false;
        if(book_id != null && books_info != null){
            books_info.remove(book_id);
            flag = true;
        }

        JSONObject result = new JSONObject();
        if(flag != false) {
            System.out.println("delete_result执行成功");
            result.put("status", "success");
        }
        else {
            System.out.println("delete_result执行失败");
            result.put("status", "fail");
        }
        System.out.println(result.toString());
        return result.toString();
    }



    @RequestMapping(value = "/uaddBook",method = RequestMethod.POST)
    public ModelAndView uaddBook(@RequestParam(value = "book_image") MultipartFile file,
                                 HttpSession session) throws Exception{

        System.out.println("执行了uaddBook");

        String book_name = request.getParameter("book_name");
        String book_author = request.getParameter("book_author");
        String book_press = request.getParameter("book_press");
        String book_date = request.getParameter("book_date");
        Integer book_number = Integer.valueOf(request.getParameter("book_number"));
        String book_image = file.getOriginalFilename();


        ModelAndView mv = new ModelAndView();
        mv.setViewName("redirect:/book/bookManage");

        if (book_name == null || book_author == null) {
            mv.addObject("tips","图书名称或作者不能为空");
            return mv;
        }else{
            try {
                if (file != null) {
                    String fileName = System.currentTimeMillis() + file.getOriginalFilename();
                    String upload_file_dir = uploadPathImg;
                    // String destFileName = uploadPathImg + fileName;

                    // 若文件不存在,则创建
                    File upload_file_dir_file = new File(upload_file_dir);
                    if (!upload_file_dir_file.exists()) {
                        upload_file_dir_file.mkdirs();
                    }

                    // 前端上传的文件复制到希望的位置
                    File targetFile = new File(upload_file_dir_file, fileName);
                    file.transferTo(targetFile);

                    // 上传图片最终的路径(String类型)
                    book_image = fileName;

                    // 插入数据库
//                    bookService.insertBookInfo(book_name,book_author,book_press,book_date,book_number,book_image);
                    books_number = book_number;
                    session.setAttribute("book_name",book_name);
                    session.setAttribute("book_press",book_press);
                    session.setAttribute("book_author",book_author);
                    session.setAttribute("book_date",book_date);
                    session.setAttribute("book_number",book_number);
                    session.setAttribute("book_image",book_image);
                    session.setAttribute("book_id",++books_id);

                    List booksInfo = new ArrayList();
                    List bookInfo = new ArrayList();

                    for(int i = 0;i < books_id;i++){
                        List bookTarget = new ArrayList();
                        bookTarget.add(book_name);
                        bookTarget.add(book_press);
                        bookTarget.add(book_author);
                        bookTarget.add(book_date);
                        bookTarget.add(book_number);
                        bookTarget.add(book_image);
                        bookTarget.add(i);
                        bookInfo.add(bookTarget);
                    }
                    booksInfo.add(bookInfo);
                    mv.addObject("booksInfo",booksInfo);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return mv;
    }
}
